﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Security.Specs.Common
{
    /// <summary>
    /// Коллекция ошибок
    /// </summary>
    public class ErrorCollection : List<ErrorReport>
    {
        public ErrorCollection() : base()
        {
        }

        public ErrorCollection(IEnumerable<ErrorReport> reports) :
            base(reports) {}

        /// <summary>
        /// Доступ к ошибкам по имени свойства
        /// </summary>
        /// <param name="propertyName">Имя свойства</param>
        /// <returns>Отчет об ошибки для свойства с указанным именем, если ничего не найдено то возвращает null</returns>
        public ErrorReport this[string propertyName]
        {
            get
            {
                return this.FirstOrDefault(e => e.PropertyName == propertyName);
            }
        }

        public new int Count(ErrorSeverity severity)
        {
            return this.Count(e => e.Severity == severity);
        }

        public bool IsEmpty()
        {
            return base.Count == 0;
        }

        public string GetFormattedErrors(ErrorSeverity severity)
        {
            return string.Join(Environment.NewLine, GetErrors(severity));
        }

        public string[] GetErrors(ErrorSeverity severity)
        {
            return this.Where(e => e.Severity == severity).Select(e => e.Message).ToArray();
        }

        public static ErrorCollection Empty()
        {
            return new ErrorCollection();
        }
    }

    public static class ErrorColollectionExtensions
    {
        public static ErrorCollection AsErrorCollection(this IEnumerable<string> messages, ErrorSeverity severity)
        {
            return new ErrorCollection(messages.Select(m => (ErrorReport) ErrorReport.Create().WithMessage(m).Severity(severity)));
        }
    }
}
